<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/***************************************************************************
 * 
 * Copyright (c) 2014 Baidu.com, Inc. All Rights Reserved
 * 
 **************************************************************************/
 
 
 
/**
 * @todo 文章控制器
 * @package controllers 
 * @file p.php
 * @author lihongliang01@baidu.com
 * @date 2014年12月9日 下午8:49:11
 * 
 *  
 **/
class P extends MY_APP_Controller {
	
	public function index($id) {
		$id = (int)$id;
		$this->loadModel('Post_model', 'post');
		$post = $this->post->findByPk($id);
		if (!isset($post[0]) || empty($post)) {
			redirect(base_url());
		}
		$this->assign['post'] = $post[0];
		$catId = $post[0]['category_id'];
		//相关文章
		$sames = $this->post->findByField(array('category_id'=>$catId), false, 5);
		$this->assign['sames'] = $sames; 
		//热门文章
		$hotArticles = $this->post->findByField(array('is_hot'=>1), 'sorts desc', 5);
		$this->assign['hot'] = $hotArticles;
		//评论
		$this->loadModel('Comments_model', 'comments');
		$comments = $this->comments->findByField(array('to_id'=>$id, 'type'=>'article'));
		$this->assign['comments'] = $comments;
		$this->display();
	}
	
	public function createComment() {
		$redirect = getRedirect();
		$lastTime = $this->session->userdata('cttime');
		if (time()-(int)$lastTime < 60) {
			echo json_encode(array('error' => '请稍后再来!'));exit;
		}
		$this->load->library('form_validation');
		$this->lang->load('template');
		
		$userName = $this->session->userdata('userName');
		if (empty($userName)) {
			json_encode(array('error'=>'请登录后发表评论!'));
			exit;
		}
		
		if ($this->form_validation->run('comments/create') == FALSE){
			echo json_encode(array('error' => validation_errors()));
			exit;
		}
		$data = $this->input->post(null,true);
		$this->loadModel('Post_model', 'post');
		$article = $this->post->findByPk((int)$data['pid']);
		if (empty($article)) {
			echo json_encode(array('error' => '该文章不存在!',));exit;
		}
		
		$comment = array(
			'username' => empty($userName) ? '匿名用户':$userName,
			'content' => $data['content'],
			'to_id' => $data['pid'],
			'type' => 'article',
			'created_at' => time(),
		);
		$this->loadModel('Comments_model', 'comment');
		if(($id = $this->comment->save($comment))!==false){
			$this->session->set_userdata(array('cttime'=>time()));
			$views = $this->load->view('p/comment', array('comment'=>$comment), true);
			$result = array('error' => 'ok','result' => $views);
			echo json_encode($result);exit;
		}else{
			echo json_encode(array('error' => 'faild'));exit;
		}
	}
}

/*End of file p.php*/
/*Location p.php */